package com.yuantong.xyerp.rest.controller.base;

import com.yuantong.xyerp.core.api.common.Constant;
import com.yuantong.xyerp.core.api.model.UserDetail;
import com.yuantong.xyerp.core.api.service.IUserService;
import com.yuantong.xyerp.rest.config.shiro.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by Jianguo.Yin on 2021-07-20.
 */
@Component
public class BaseController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private IUserService userService;


    protected String getCauseId(HttpServletRequest request){
        UserDetail subject = getSubject(request);
        String dataRights = subject.getDataRights();

        if (Objects.equals(Constant.DataRight_Department,dataRights)){
            return subject.getOrganizationId();
        }
        if (Objects.equals(Constant.DataRight_Personal,dataRights)) {
            return subject.getId();
        }
        return null;
    }



    protected String getToken(HttpServletRequest request) {
        // 获取请求头信息authorization信息
        String authHeader = request.getHeader(JwtUtil.AUTH_HEADER_KEY);
        return authHeader.substring(7);
    }

    protected UserDetail getSubject(HttpServletRequest request) {
        String loginName = JwtUtil.getClaim(getToken(request),Constant.LOGIN_NAME);
        if (Boolean.TRUE.equals(redisTemplate.hasKey(Constant.PREFIX_USER_CACHE + loginName)))
            return (UserDetail) redisTemplate.opsForValue().get(Constant.PREFIX_USER_CACHE + loginName);
        return userService.selectOneByUserDetail(new UserDetail().setLoginName(loginName));
    }
}
